package taskoauthproject;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AppEngineCredentialStore;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.Calendar.Events;
import com.google.api.services.calendar.Calendar.Events.Get;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.tasks.Tasks;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.base.Preconditions;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import sun.print.resources.serviceui;

/**
 * Utility class for JDO persistence, OAuth flow helpers, and others.
 * 
 */
public class Utils {

	/** Global instance of the HTTP transport. */
	  static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

	  /** Global instance of the JSON factory. */
	  static final JsonFactory JSON_FACTORY = new JacksonFactory();

	  private static GoogleClientSecrets clientSecrets = null;

	  
	  private static final List<String> SCOPES = Arrays.asList(
			  "https://www.googleapis.com/auth/drive",
		      "https://www.googleapis.com/auth/drive.file",
		      "https://www.googleapis.com/auth/drive.metadata.readonly",
		      "https://www.googleapis.com/auth/drive.readonly",
		      "https://www.googleapis.com/auth/userinfo.email",
		      "https://www.googleapis.com/auth/userinfo.profile",
		      "https://www.googleapis.com/auth/calendar",
		      "https://www.googleapis.com/auth/tasks");
	  
	  
	  static GoogleClientSecrets getClientCredential() throws IOException {
	    if (clientSecrets == null) {
	      clientSecrets = GoogleClientSecrets.load(
	          JSON_FACTORY, Utils.class.getResourceAsStream("/client_secrets.json"));
	      Preconditions.checkArgument(!clientSecrets.getDetails().getClientId().startsWith("Enter ")
	          && !clientSecrets.getDetails().getClientSecret().startsWith("Enter "),
	          "Download client_secrets.json file from https://code.google.com/apis/console/?api=calendar "
	          + "into calendar-appengine-sample/src/main/resources/client_secrets.json");
	    }
	    return clientSecrets;
	  }

	  static String getRedirectUri(HttpServletRequest req) {
	    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
	    url.setRawPath("/oauth2callback");
	    return url.build();
	  }

	  static GoogleAuthorizationCodeFlow newFlow() throws IOException {
	    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
	        getClientCredential(), SCOPES).setCredentialStore(
	        new AppEngineCredentialStore()).setAccessType("offline").build();
	  }

	  public static Calendar loadCalendarClient() throws IOException {
	    String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
	    
	    System.out.println(UserServiceFactory.getUserService().getCurrentUser().getUserId());
	    Credential credential = newFlow().loadCredential(userId);
	    return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
	  }
	  
	  public static Calendar loadCalendarClient(String userId) throws IOException {
		    System.out.println(UserServiceFactory.getUserService().getCurrentUser());
		    Credential credential = newFlow().loadCredential(userId);
		    return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
		  }
	  
	  
	  
	 
//	  static GoogleAuthorizationCodeFlow newDriveFlow() throws IOException {
////		    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
////		        getClientCredential(), Collections.singleton(SCOPES)).setCredentialStore(
////		        new AppEngineCredentialStore()).setAccessType("online")
////		        .setApprovalPrompt("auto").build();
//		  
//		  	return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(), SCOPES)
//		  	.setAccessType("offline").setApprovalPrompt("force").build();
//		  }
	  
	  public static Drive loadDriveService() throws IOException {
		  
		  String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
		  Credential credential = newFlow().loadCredential(userId);
		  
		  return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
	  }
	  
	  
	  public static Tasks loadTaskService() throws IOException {
		  
		  String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
		  Credential credential = newFlow().loadCredential(userId);
		  
		  return new Tasks.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
	  }
	  
	  /**
	   * Returns an {@link IOException} (but not a subclass) in order to work around restrictive GWT
	   * serialization policy.
	   */
	  static IOException wrappedIOException(IOException e) {
	    if (e.getClass() == IOException.class) {
	      return e;
	    }
	    return new IOException(e.getMessage());
	  }

	  private Utils() {
	  }
}